<?php
// 应用公共文件
use think\facade\Log;
use think\response\Json;
use PHPMailer\PHPMailer\PHPMailer;

function show(int $status, string $message = 'error', array $data = null, int $httpStatus = 200): Json
{
    $result = [
        'code'   => 0,
        'result' => [
            'msg'    => $message,
            'status' => $status,
        ]
    ];
    if ($data) {
        $result['result']['data'] = $data;
    }
    return json($result, $httpStatus);
}

function showList(int $code, string $message = 'error', array $data = null, int $count = 0, int $httpStatus = 200): Json
{
    $result = [
        'code'  => $code,
        'msg'   => $message,
        'data'  => $data,
        'count' => $count,
    ];

    return json($result, $httpStatus);
}

function getRandomStr($n): string
{
    $characters   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $n; $i++) {
        $index        = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

function encryptPwd(string $pwd): string
{
    return getRandomStr(5) . base64_encode($pwd);
}

function decryptPwd(string $pwd): string
{
    return base64_decode(substr($pwd, 5));
}

function isMobile(): bool
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        return (bool)stristr($_SERVER['HTTP_VIA'], "wap");// 找不到为flase,否则为TRUE
    }
    // 判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientKeywords = array(
            'mobile',
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientKeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    if (isset ($_SERVER['HTTP_ACCEPT'])) { // 协议法，因为有可能不准确，放到最后判断
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== FALSE) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === FALSE || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

function cmsSubstr($string, $len = 20, $end = '...')
{
    if (mb_strlen($string, 'utf-8') < $len) {
        return $string;
    }

    return mb_substr($string, 0, $len, 'utf-8') . $end;
}

function underScoreToCamelCase($string, $capitalizeFirstCharacter = false)
{
    $str = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
    if (!$capitalizeFirstCharacter) {
        $str = lcfirst($str);
    }
    return $str;
}

function sendEmail(array $emailServer, array $emailReceiver): bool
{
    $emailHost = $emailServer['emailHost'] ?? '';
    $emailUser = $emailServer['emailUser'] ?? '';
    $emailPass = $emailServer['emailPass'] ?? '';
    $emailPort = $emailServer['emailPort'] ?? 0;
    if (empty($emailHost) || empty($emailUser) || empty($emailPass) || empty($emailPort)) {
        return false;
    }

    $emailObject  = $emailReceiver['emailObject'] ?? '';
    $emailBody    = $emailReceiver['emailBody'] ?? '';
    $receiveEmail = $emailReceiver['receiveEmail'] ?? '';
    if (empty($emailObject) || empty($emailBody) || empty($receiveEmail)) {
        return false;
    }

    if (!strstr($receiveEmail, '@')) {
        return false;
    }

    $mail = new PHPMailer(true);
    try {
        // 服务器设置
        $mail->isSMTP();
        $mail->Host       = $emailHost;
        $mail->SMTPAuth   = true;
        $mail->Username   = $emailUser;
        $mail->Password   = $emailPass;
        $mail->SMTPSecure = $emailPort == 465 ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $emailPort;

        // 邮件设置
        $mail->setFrom($emailUser, 'cms');
        $mail->addAddress($receiveEmail);

        // 邮件内容
        $mail->isHTML(true);
        $mail->Subject     = $emailObject;
        $mail->Body        = $emailBody;
        $mail->CharSet     = 'UTF-8';
        $mail->ContentType = 'text/html; charset=utf-8';

        // 发送邮件
        $mail->send();
    } catch (\Exception $e) {
        Log::error(sprintf('邮件发送失败:%s', $e->getMessage()));
        return false;
    }

    return true;
}

function sendAlarmEmail(string $emailObject, string $emailBody): bool
{
    $emailHost     = env('alarm.EMAIL_HOST', '');
    $emailUser     = env('alarm.EMAIL_USER', '');
    $emailPass     = env('alarm.EMAIL_PASS', '');
    $emailPort     = env('alarm.EMAIL_PORT', 0);
    $receiveEmail  = env('alarm.EMAIL_RECEIVER', '');
    $emailServer   = ['emailHost' => $emailHost, 'emailUser' => $emailUser, 'emailPass' => $emailPass, 'emailPort' => $emailPort];
    $emailReceiver = ['emailObject' => $emailObject, 'emailBody' => $emailBody, 'receiveEmail' => $receiveEmail];

    return sendEmail($emailServer, $emailReceiver);
}

function logErr(string $title, string $content)
{
    Log::error(sprintf('标题:%s,内容:%s', $title, $content));
    $emailMessage = sprintf("%s<br>request_uri：%s", str_replace(",", "<br/>", $content), $_SERVER['REQUEST_URI']);
    sendAlarmEmail('【站点应用告警】' . $title, $emailMessage);
}
